import { useEffect, useState } from "react"
import { Table, Input, Button, Row, Col, Modal } from 'antd'
import { useDispatch, useSelector } from "react-redux"
import { IState } from '../../store/reducer'
import { set_list, delete_list, edit_list } from '../../store/actions'
import { debounce } from '../../utils/debounce'
const App: React.FC = () => {
	const dispatch = useDispatch()
	// 获取仓库数据
	const list = useSelector((state: IState) => {
		return [...state.list]
	})
	// 搜索的数据结果
	const [searchList, setSearchList] = useState(list)

	// 搜索函数防抖 多次调用无效  只会执行最后一次
	const handleSearch = debounce((value) => {
		const newList = list.filter(v => v.title.includes(value))
		setSearchList(newList)
	})
	// 删除数据函数
	const handleDelete = (item) => {
		Modal.confirm({
			title: '确认要删除吗？',
			onOk() {
				dispatch(delete_list(item))
			}
		})

	}
	// 弹框状态 
	const [isModalVisible, setIsModalVisible] = useState(false);
	// 正在修改的数据
	const [currItem, setCurrItem] = useState({})
	const showModal = (item) => {
		setIsModalVisible(true)
		setCurrItem({ ...item })
	};

	const handleOk = () => {
		setIsModalVisible(false);
		dispatch(edit_list(currItem))
	};

	const handleCancel = () => {
		setIsModalVisible(false);
	};

	useEffect(() => {
		handleSearch('')
	}, [list])

	// 头部数据
	const columns = [{
		key: 'title',
		dataIndex: 'title',
		title: '标题'
	}, {
		key: 'desc',
		dataIndex: 'desc',
		title: '描述'
	}, {
		key: 'url',
		dataIndex: 'url',
		title: '图片',
		render(url) {
			return <img src={url} alt="" width={20} height={20} />
		}
	}, {
		key: 'type',
		dataIndex: 'type',
		title: '类型'
	}, {
		key: 'del',
		title: '操作',
		render(text, record) {
			return <div>
				<Button danger onClick={() => handleDelete(record)}>删除</Button>
				<Button type="primary" onClick={() => showModal(record)}>编辑</Button>
			</div>
		}
	}]
	// 请求列表数据
	useEffect(() => {
		// 分发action
		list.length === 0 && dispatch(set_list())
	}, [])

	return (
		<div>
			<div>
				<Row>
					<Col span={6}>
						<Input placeholder="Basic usage" onChange={debounce((e) => handleSearch(e.target.value))} />
					</Col>
					<Col span={2}>
						<Button>搜索</Button>
					</Col>
				</Row>
			</div>
			<Table dataSource={list} columns={columns}></Table>
			<Modal title="修改数据" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
				<p>
					<Input value={(currItem as any).title} onChange={e => setCurrItem({ ...currItem, title: e.target.value })}></Input>
				</p>
				<p>
					<Input value={(currItem as any).desc} onChange={e => setCurrItem({ ...currItem, desc: e.target.value })}></Input>
				</p>
				<p>
					<Input value={(currItem as any).type} onChange={e => setCurrItem({ ...currItem, type: e.target.value })}></Input>
				</p>
			</Modal>
		</div>
	)
}

export default App